var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var httpget = require('http');
var bodyParser = require('body-parser');
var session = require('express-session');
var s_db = require('./dbwrap_construct_1.js');
var fs = require('fs');
var SMSClient = require('@alicloud/sms-sdk');
var child_process = require('child_process');
var methods = require('methods');
var tcpcache = require('./tcpcache.js');
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var md5 = require("md5");
//在线
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'BIM');
    // res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
app.use(express.static(__dirname + '/app'));
http.listen(9069, function () {
    console.log('info',"listening on *:9069 construct");
});
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 10//过期时间设置(单位毫秒)
    }
}));
app.use(function (req, res, next) {
    var url = req.url;
    if (url == '/userlogin' || url.indexOf('/sensor_data') >= 0){
        next();
        return;
    }
    if (!req.session.user){
        res.send({ret:-3,info:"session过期"});
        return;
    }else if (req.session.user){
        next();
    }
});
// 通过启动子进程启动tcpserver
var process_start = child_process.fork(__dirname+'/process.js');
process_start.on('message', function (m) {
    console.log('PARENT got message:', m);
}); 
function server_db() {
    return s_db;
}
// ************************函数*****************************
// ********************施工管理接口******************************
// **********************公用接口********************************
function post_select_data(req,res,tablename,fields) {
    var page = null;
    if (req.body.page) {
        page = req.body.page;
    } else {
        page = req.body.currentPage;
    }
    var limit = req.body.rows;
    var sidx = req.body.sidx;
    var sord = req.body.sord;
    if (sidx == null)
        sidx = 1;  
    if (page == null)
        page = 1;
    if (limit == null)
        limit = 10;    
    server_db().db_info_type_page(req,fields,tablename, page, limit,sidx,sord,function(ret,info){
            info.ret = ret;
            // if (tablename == 'logfile') {
            //     console.log('info',info);
            // }           
            res.send(info);   
    });
};
function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                return true;
            } catch(e) {
                return false;
            }
        }else{
            return false;
        }
}
// 项目：1：代表项目编辑权限、2：代表设备编辑权限、4：代表查看权限
function project_power(power,num){
        var arr_pro = [];
        if (isJSON(power) == true){
            power = JSON.parse(power);
            for (var i = 0; i < power.length; i++) {
                var projectid = power[i].projectid;
                var current_power = power[i].power;
                if ((current_power & num) == num) {
                  arr_pro.push(projectid);
                }
            }
        }        
        return arr_pro;
}
// **********************前台接口********************************
// 账号密码登录
app.post('/userlogin', function (req, res) {
    var id = req.body.id;
    var pass = req.body.pass;
    var tablename = 'user';
    if (id == null || pass == null) {
        res.sendStatus(404);
        return;
    }
    else {
        pass = md5(pass);
        var query = {
            id:"="+id,
            pass:"="+pass
        };
        server_db().db_get_detailuser(tablename,query, function (ret, info,power) {
            if (ret == -1){
                res.send({ret:-1});
            }
            else if (ret == 0) {
                res.send({ret:0});
            }
            else if (ret == 1) {
                req.session.user = id;               
                if (info.fid == '1'){//管理员
                    req.session.power = 'all';
                    req.session.fid = id;
                }else{//普通用户
                    req.session.fid = info.fid;
                    req.session.power = power;
                }                
                res.send({ ret: 1,info: info,power:req.session.power});               
            }
        });
    }
});
app.get('/logout', function (req, res) {
    req.session.user = null;
    req.session.error = null;
    res.redirect('/login.html');
});
app.get('/session_user', function (req, res) {
    // console.log(req.session.fid);
    res.send({ret:1,user:req.session.user,fid:req.session.fid,power:req.session.power});
});
// **********************后台接口*************************************

// ***************************get接口***************************************
// 查询详情数据 (url?a==1) 单条数据  
app.get('/detail/:table', function (req, res) {
    var query = req.query;
    var tablename = req.params.table;
    if (tablename == null || query == null) {
        res.sendStatus(404);
        return;
    }
    else {
        server_db().db_get_detail(tablename,query, function (ret, info) {
            res.send({ret:ret,info:info});
        });
    }
});
//2.0 获取数据不分页  url?a==1
app.get("/list_nopage/:table", function (req, res) {
    var table = req.params.table;
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var fields = '*';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
            req.query.fid = req.session.fid;
     
    }else{
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,info:[]});
            return;
        }                    
        if(table == "project"){//通过项目id获取项目列表
            req.field_arr = arr_pro; 
            req.field = 'id';               
        }
        else if(table == "device"){//通过项目id获取设备列表
            req.field_arr = arr_pro; 
            req.field = 'projectid';
        }
        else if (table == 'log') {//通过设备id获取log列表
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++){
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','desc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }
                 }else{
                    res.send({ ret: ret, info: info});
                 }
            });
            return;
        }
    }
    server_db().db_select_list(req.field,req.field_arr,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});

// 2.1 不分页  url?a==1
app.get("/select_idname/:table", function (req, res) {
    var table = req.params.table;
    var fields = 'id,name';
     if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.query.fid = req.session.fid;
    }else{
        var arr_pro = project_power(power,4);
        if (table == 'project') {
            if (arr_pro.length > 0) {
               server_db().db_select_where_in('id',arr_pro,fields,table,function(ret,info){
                  res.send({ret:1,info:info});
               })
            }else{
                  res.send({ret:1,info:[]})
            }
            return;           
        }else{
            req.query.fid = req.session.fid;
        }
    }
    server_db().db_select_list(null,null,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});
// 2.1 不分页  获取所有的设备
app.get("/select_deviceid", function (req, res) {
    var table = 'device';
    var fields = 'id,deviceid';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.query.fid = req.session.fid;
    }
    server_db().db_select_list(null,null,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});
// 不分页历史数据曲线：查询指定字段 url?deviceid=1&time=2017-01-01,2017-02-02
// log表
app.get("/history_data",function(req,res){
    var table = 'log';
    var fields = 'press,temp,time';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        // 获取设备id
        req.query.fid = req.session.fid;
        server_db().db_select_list(null, null,req.query, fields ,table,'time','asc', function(ret1,info1){
             res.send({ ret: ret1, info: info1 });
        });
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
                return;
            }
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','asc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }                  
                 }else{
                    res.send({ret:ret,info:info});
                 } 
            });
    }
    
})
app.get("/history_data_yk",function(req,res){
    var table = 'yk_datasub';
    var fields = 'deviceid,value,time';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        // 获取设备id
        req.query.fid = req.session.fid;
        server_db().db_select_list(null, null,req.query, fields ,table,'time','asc', function(ret1,info1){
             res.send({ ret: ret1, info: info1 });
        });
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
                return;
            }
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','asc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }                  
                 }else{
                    res.send({ret:ret,info:info});
                 } 
            });
    }
    
})



// 获取实时数据
app.get("/actual_data/:port",function(req,res){
    var port = parseInt(req.params.port);
    var power = req.session.power;
    if (port == null || port == '') {
        port = 8051;
    }
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {//管理员
        //获取设备id
        server_db().db_select_list(null,null,{fid:req.session.fid}, 'id,deviceid', 'device',null,null, function(ret,info){
           if (ret == 1){
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                // console.log('deviceid',deviceid_arr);
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(8051,deviceid_arr);
                    // console.log(data);
                    res.send({ret:1,info:data});
                }else{
                    res.send({ret:1,info:[]});
                }
                
            }else{
                   res.send({ret:ret,info:info});
            }
        });
    }else{//普通用户
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,info:[]});
            return;
        }
        // 获取设备id
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
             if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(8051,deviceid_arr);
                    res.send({ret:1,info:data});
                }else{
                    res.send({ret:1,info:[]});
                }
             }else{
                res.send({ret:ret,info:info});
             }
        });
    }
});
//获取设备总数，报警设备，正常设备
app.get('/device_count',function(req,res){
    var power = req.session.power;
    var total = 0;
    var warn = 0;
    var ok = 0;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {//管理员
       server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid},function(ret,info){
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null,null,'deviceid','warn_report',{fid:'='+req.session.fid},function(ret1,info1){
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }else{
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }
               })
            }
       })
    }else if (isJSON(power) == true){//有权限普通用户
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,total:total,warn:warn,ok:ok});
            return;
        }
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
            if (ret == 1) {               
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                total = deviceid_arr.length;
                if (deviceid_arr.length <= 0) {
                    res.send({ret:1,total:total,warn:warn,ok:ok})
                }else{
                    server_db().db_get_count('deviceid',deviceid_arr,'deviceid','warn_report',null,function(ret1,info1){
                        if (ret1 == 1) {
                            warn = info1;
                            ok = total - warn;
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }else{
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }
                   })
                }               
            }
       })
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
        
})

// 获取表的所有列
app.get('/table_columns/:table',function(req,res){
    var table = req.params.table;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    server_db().db_table_columns(table,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
//获取设备总数，报警设备，正常设备
app.get('/device_count',function(req,res){
    var power = req.session.power;
    var total = 0;
    var warn = 0;
    var ok = 0;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'administrator'){//超级管理员
        server_db().db_get_count(null,null,'deviceid','device',null,function(ret,info){
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }else{
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }
               })
            }
       })
    }else if (power == 'all') {//管理员
       server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid},function(ret,info){
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }else{
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }
               })
            }
       })
    }else if (isJSON(power) == true){//有权限普通用户
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,total:total,warn:warn,ok:ok});
            return;
        }
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
            if (ret == 1) {               
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                total = deviceid_arr.length;
                if (deviceid_arr.length <= 0) {
                    res.send({ret:1,total:total,warn:warn,ok:ok})
                }else{
                    server_db().db_get_count('deviceid',deviceid_arr,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                        // console.log(ret1,info1);
                        if (ret1 == 1) {
                            warn = info1;
                            ok = total - warn;
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }else{
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }
                   })
                }               
            }
       })
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
        
})

//钱波新增加一个接口: 油库的数据存储
app.post('/sensor_data_1/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    tcpcache.tcpcallback(port, data, null, function (r_port, r_data) {
        // 存入数据库
        // console.log('save',r_port,r_data);
        server_db().db_get_detail_field('device', { port: r_port, deviceid: r_data.deviceid }, 'fid,projectid', function (ret, info) {
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // console.log(r_data);
                server_db().db_info_insert(r_data, 'yk_datasub', function (ret, info) {
                    res.send({ ret: ret, info: info });
                })
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
// ***************************post接口 业务层***************************************
// 分页查询  url?a==1
// 对表的分页查询：信息列表 select:(search,select)
app.post('/list/select/:table', function (req, res) {
    // log_start.control("debug",req.body);
    // console.log(req.query);
    // console.log("power",req.session.fid,req.session.power);
    var table = req.params.table;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if(power == 'all'){
            req.query.fid = req.session.fid;
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
            }else{
                if(table == "project"){//通过项目id获取项目列表
                    req.field_arr = arr_pro; 
                    req.field = 'id';               
                }
                else if(table == "device"){//通过项目id获取设备列表
                    req.field_arr = arr_pro; 
                    req.field = 'projectid';
                }
                else if (table == 'log') {//通过设备id获取log列表
                    // 获取设备id
                    server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                         if (ret == 1) {
                            var deviceid_arr = [];
                            for (var i = 0; i < info.length; i++) {
                                var obj = info[i];
                                deviceid_arr.push(obj.deviceid);
                            }
                            if (deviceid_arr.length > 0){
                                req.field_arr = deviceid_arr; 
                                req.field = 'deviceid';
                                post_select_data(req, res, table,null);    
                            }else{
                                res.send({ret:1,info:[]});
                            }
                         }
                    });
                    return;
                }else{
                    req.query.fid = req.session.fid;
                }
            }                     
            
    }
    post_select_data(req, res, table,null);        
});
// 添加一条数据
app.post('/data/:table',function(req,res){
    var table = req.params.table;
    var c = Object.keys(req.body);
    if (table == null || table == "" || c.length <= 0){
        res.sendStatus(404);
        return;
    }
    if (table == 'user') {
        req.body.pass = md5('111111');
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.body.fid = req.session.fid;
    }else{
        if (table == 'logfile') {
            req.body.fid = req.session.fid;
        }else if (table == 'device'){
            var arr_pro = project_power(power,2);
            var index = arr_pro.indexOf(parseInt(req.body.projectid));
            req.body.fid = req.session.fid;
            if (index < 0){
                res.send({ret:-1,info:'没有权限或者没有绑定现有项目'});
                return;
            }
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }     
    }
    server_db().db_info_insert(req.body,table, function (ret, info) {
           if (ret == 1) {
              res.send({ret:ret,info:info});
           }else{
              res.send({ret:-1,info:info});
           }
            
    });
});
// 添加多条数据 body: [{name:1},{name:2}]
app.post('/data_mul/:table',function(req,res){
    var table = req.params.table;
    if (table == null || table == "" || JSON.stringify(req.body) == '{}'){
        res.sendStatus(404);
        return;
    }
    server_db().db_info_insert_mul(table,req.body,function(ret,info){
        res.send({ret:ret,info:info});
    })
});

// 创建协议(建表)
// var define ={
//    tableName: "alarm7",//报警信息表
//    fields: {
//        id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" },
//        type: { des: "类型", type: "varchar(110)" },
//        des: { des: "描述", type: "varchar(110)" },
//        condition1: { des: "报警条件json", type: "varchar(210)" },
//        grade: { des: "等级", type: "varchar(110)" }
//    }
// }
app.post('/create_protocol',function(req,res){
    var c = Object.keys(req.body);
    if (c.length <= 0){
        res.sendStatus(404);
        return;
    }
    var table = 'protocol';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.body.fid = req.session.fid;        
    }else{
        res.send({ret:-4,info:'没有权限'});
        return; 
    }
    server_db().db_info_insert(req.body,table, function (ret, info) {
           if (ret == 1) {
              var define ={
                   tableName: "protocol_"+info,//报警信息表
                   fields: {
                       id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" }
                   }
              }
              server_db().db_create_table(define,function(ret1,info1){
                    res.send({ret:ret1,info:info1});
              })
           }else{
              res.send({ret:-1,info:info});
           }
            
    });   
});
// 添加列
// body:{name:"testfieldss",type:"int(12)",des:"this is a test",first:true}
app.post('/add_column/:table',function(req,res){
   var table = req.params.table;
    if (table == null || table == "" || req.body == null){
        res.sendStatus(404);
        return;
    }
    server_db().db_add_column(table,req.body,function(res,info){
        res.send({ret:ret,info:info});
    })
});
// ***************************put接口***************************************
// 下发查询的接口
app.post('/query_device',function(req,res){
    var deviceid = req.body.deviceid;
    if (deviceid == null || deviceid == '') {
        res.sendStatus(404);
        return;
    }
    req.body.cmd = 'read';
    // console.log(req.body);
    var data = JSON.stringify(req.body);
    // var message = Buffer.from('00000000');
    client.send(data, 0, data.length, 8051, 'localhost');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var data = tcpcache.get_port_device_data_1(8051,deviceid);
    res.send({ret:1,info:data});
});
// 参数设置的接口
app.put('/edit_device',function(req,res){
    var deviceid = req.query.deviceid;
    var id = req.query.id;
    var table = 'device';
    if (deviceid != null && deviceid.indexOf('=') >= 0) {
        deviceid = deviceid.match(/=(\S*)/)[1];
    }
    if (deviceid == null || deviceid == '' || id == '' || id == null) {
        res.sendStatus(404);
        return;
    }
    var write_data = req.body;
    // var cun_data = {};
    // Object.assign(cun_data,req.body);
    // var message = Buffer.from('00000000');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;    
    }else if (power == 'all') {
        req.body.fid = req.session.fid; 
    }else if (power == 'administrator'){

    }else if (isJSON(power) == true){//有权限普通用户
            var arr_pro = project_power(power,2);         
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = req.query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        // console.log(power,arr_pro,deviceid_arr,req.query.id,str);
                        if (index >= 0) {
                            server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                               res.send({ret:ret,info:info}); 
                               if (ret == 1) {
                                  write_data.deviceid = deviceid;
                                  write_data.cmd = 'write';
                                  var data = JSON.stringify(write_data);
                                  client.send(data, 0, data.length, 8051, 'localhost');
                               }
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
       res.send({ret:ret,info:info}); 
       if (ret == 1) {
          write_data.deviceid = deviceid;
          write_data.cmd = 'write';
          var data = JSON.stringify(write_data);
          client.send(data, 0, data.length, 8051, 'localhost');
       }
    });
});
// 修改密码 编辑一条数据 url?id==5
app.put('/modifypass',function(req,res){
   var table = 'user';
   var pass = req.body.pass;
   var oldpass = req.body.oldpass;
   var c = Object.keys(req.query);
   if (pass == null || pass == '' || c.length <= 0 || oldpass == null || oldpass == '') {
      res.sendStatus(404);
      return;
    }
    delete req.body.oldpass;
    req.body.pass = md5(pass);
    oldpass = md5(oldpass);
    server_db().db_get_detailuser(table,req.query, function (ret, info,power) {
            if (ret == -1){
                res.send({ret:-1});
            }
            else if (ret == 0) {
                res.send({ret:0});
            }
            else if (ret == 1) {
                if (info.pass == oldpass) {
                    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                       res.send({ret:ret,info:info}); 
                    });
                    
                }else{
                    res.send({ret:-1,info:'原始密码错误'})
                }                            
            }
    });
});
// 编辑一条数据 url?id==5
app.put('/data/:table',function(req,res){
    var table = req.params.table;
    var c = Object.keys(req.query);
    if (table == null || table == "" || req.body == null || c.length <= 0){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        if (table == 'user') {
            req.body.fid = req.session.fid;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }        
    }else if (power == 'all') {
        if (table == 'user' && (req.query.id == ("="+req.session.fid) || req.query.id == req.session.fid)) {
            req.body.fid = '1';
        }else{
            req.body.fid = req.session.fid;
        }
        
    }else{//普通用户
        if (table == 'device'){
            var arr_pro = project_power(power,2);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = req.query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        if (index >= 0) {
                            server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                               res.send({ret:ret,info:info}); 
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
        }else if(table == 'project'){
            var arr_pro = project_power(power,1);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                var str = req.query.id;                        
                if (str != null && str.indexOf('=') >= 0) {
                    str = str.match(/=(\S*)/)[1];
                }
                var index = arr_pro.indexOf(parseInt(str));
                if (index >= 0) {
                    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                       res.send({ret:ret,info:info}); 
                    });
                }else{
                    res.send({ret:-4,info:'没有权限'});
                }
            }
            return;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }
    }
    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
       res.send({ret:ret,info:info}); 
    });
});

// 修改表的列
app.put('/column/:table/:columnname',function(req,res){
    var table = req.params.table;
    var column = req.params.columnname;
    if (table == null || table == "" || req.body == null || column == null){
        res.sendStatus(404);
        return;
    }
    server_db().db_edit_column(table,column,req.body,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// ***************************delete接口***************************************
// 删除一条数据 url?id==123
app.delete('/data/:table',function(req,res){
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        
    }else{
        if (table == 'device'){
            var arr_pro = project_power(power,2);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        if (index >= 0) {
                            server_db().db_info_delete(query,table, function (ret, info) {
                               res.send({ret:ret,info:info}); 
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }       
    }
    server_db().db_info_delete(query,table, function (ret, info) {
       res.send({ret:ret,info:info}); 
    });
});
// 删除多行数据 url?field=['a','b']
app.delete('/data_mul/:table',function(req,res){
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == "" || JSON.stringify(query) == '{}'){
        res.sendStatus(404);
        return;
    }
    var field,arr;
    for (var key in query) {
        field = key;
        arr = query[key];
    }
    server_db().db_info_delete_mul(table,field,arr,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// 删除一个协议(删除协议，删除协议的数据表)
app.delete('/sensor/protocol',function(req,res){
    var table = 'protocol';
    var query = req.query;
    var table2 = table+'_';
    var c = Object.keys(req.query);
    if (c.length <= 0 || query.id == null){
        res.sendStatus(404);
        return;
    }
    if (query.id[0] == "=") {
        var len =  query.id.length;
        table2 += query.id.substr(1,len-1);
    }else{
        table2 += query.id;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
    server_db().db_info_delete(query,table, function (ret, info) {
        if (ret == 1) {
            server_db().db_delete_table(table2,function(ret1,info1){
                res.send({ret:ret1,info:info1});
            })
        }else{
            res.send({ret:-1,info:info});
        }
    });
    
});
// 删除表中的一列
app.delete('/column/:table/:column',function(req,res){
    var table = req.params.table;
    var column = req.params.column;
    if (table == null || table == '' || column == null || column == '') {
        res.sendStatus(404);
        return;
    }
    server_db().db_delete_column(table,column,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// ********************************函数******************************************
